package com.leyantech.ecp.agenx.session.manager.handler;

import static com.leyantech.ecp.agenx.common.config.ConfigManager.ASSISTANT_EVENT_TOPIC;
import static com.leyantech.ecp.agenx.session.manager.handler.AssistantConfigHandler.toAssistant;

import com.leyantech.chaos.kafka.KafkaProducerStringClient;
import com.leyantech.ecp.agenx.common.entity.client.config.ReplyModeConfig;
import com.leyantech.ecp.agenx.common.entity.client.config.ReplyModeConfig.Config;
import com.leyantech.ecp.agenx.common.redis.RedissonOperation;
import com.leyantech.ecp.agenx.common.redis.entity.OnlineAssistantSession;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.vertx.core.json.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;

/**
 * @author eahau, {@literal <eahau@foxmail.com>}
 * @date 2022-12-06.
 */
@Slf4j
@Singleton
public class ReplyModeConfigHandler implements ConfigHandler {

  private final KafkaProducerStringClient producer;

  @Inject
  public ReplyModeConfigHandler(KafkaProducerStringClient producer) {
    this.producer = producer;
  }

  @Override
  public String configName() {
    return "REPLY_MODE_CONFIG";
  }

  @Override
  public void handle(JsonObject jsonObject) {
    final String sid = jsonObject.getString("sid");
    final String aid = jsonObject.getString("aid");
    final long timestamp = jsonObject.getLong("ts");

    final ReplyModeConfig replyModeConfig = jsonObject.mapTo(ReplyModeConfig.class);

    final List<Config> configs;
    if (replyModeConfig == null
        || CollectionUtils.isEmpty(configs = replyModeConfig.getConfigs())) {
      log.warn("invalid ReplyModeConfig {}", replyModeConfig);
      return;
    }

    final Config config = configs.get(0);

    final OnlineAssistantSession onlineAssistant = RedissonOperation.STORE_ASSISTANT
        .executor(sid)
        .get(map -> map.computeIfPresent(aid, (ignore, existValue) -> {
              existValue.setServiceMode(config.getCode());
              existValue.setFunctions(config.getFunction());
              existValue.setAction("CONFIG_CHANGED");
              existValue.setTimestamp(timestamp);
              return existValue;
            }
        ), "replyModeChange");

    if (onlineAssistant != null) {
      final String key = String.join(".", sid, aid);
      producer.send(ASSISTANT_EVENT_TOPIC.get(), key, toAssistant(onlineAssistant).toString());
    }
  }

}
